import React, { Component } from 'react'
import { Button, Col, Dropdown, Icon, Menu, message, Modal, Popconfirm, Row, Switch, Table } from 'antd'
import '../../less/index.less'
import '../../less/program-list.less'
import { connect } from 'react-redux'
import { Link, withRouter } from 'react-router-dom'
import EditableCell from '../common/editable-cell'
import * as actions from '../../actions/progarm'
import DateCell from '../common/date-cell'
import SelectStatus from '../common/select-status-cell'
import { TwsReactMarkdownEditor } from 'tws-antd'
import { getUploadUrl } from '../../constant/upload-url'
import { CopyToClipboard } from 'react-copy-to-clipboard'
import { convertContent } from '../../constant/lang-util'
import { FormattedMessage } from 'react-intl'

class ProgramManagement extends Component {
  constructor () {
    super()
    this.state = {
      expandIconAsCell: false,
      expandRowByClick: true,
      expandedRowKeys: [],
      introduction: '',
      introductionIcon: 'edit',
      editId: 0,
      deleteProgram: '',
      page: 1,
      pageSize: 20,
      modalVisible: false,
      content: '',
      programName: ''
    }
  }

  setModalVisible (modalVisible) {
    this.setState({modalVisible})
  }

  onChange (page, pageSize) {
    this.setState({page})
    this.props.getPrograms(page, pageSize)
  }

  onDelete (record) {
    const {page, pageSize} = this.state
    this.state.deleteProgram.trim() === record.title.trim()
      ? this.props.deleteProgram(record.id, page, pageSize, () => {
        this.setModalVisible(false)
      }) : message.info(convertContent('请输入正确的训练营名称'))
  }

  handleAdd () {
    const newProgram = {
      title: '',
      startTime: null,
      endTime: null,
      category: '付费'
    }
    this.setState({page: 1})
    this.props.addProgram(newProgram)
  }

  onCellChange (value, type, program) {
    program[type] = value
    const {page, pageSize} = this.state
    this.props.editProgram(program, page, pageSize)
  }

  changeShow (programId) {
    return '/program/' + programId
  }

  addIntroduction (program) {
    this.setState({
      expandedRowKeys: [],
      introductionIcon: 'edit',
      introduction: '',
      isFixed: true
    })
    const introduction = this.state.introduction ? this.state.introduction : program.introduction
    this.onCellChange(introduction, 'introduction', program)
  }

  switchIcon (record) {
    if (this.state.introductionIcon === 'check' && record.id === this.state.editId) {
      return <Icon type='check' onClick={this.addIntroduction.bind(this, record)}/>
    } else {
      return <Icon type='edit' onClick={this.operateIntroduction.bind(this, record)}/>
    }
  }

  operateIntroduction (record) {
    this.onExpandedRowsChange(record)
    this.setState({
      introductionIcon: 'check',
      editId: record.id,
      isFixed: false
    })
  }

  onExpandedRowsChange (rows) {
    this.setState({
      expandedRowKeys: [rows.id]
    })
  }

  getIntroduction (introduction) {
    this.setState({introduction})
  }

  expandedRowRender (settings, record) {
    return <div>
      <TwsReactMarkdownEditor
        action={getUploadUrl(settings.appContextPath)}
        value={record.introduction} onChange={this.getIntroduction.bind(this)}/>
      <Button type='primary' className='margin-t-2' onClick={this.addIntroduction.bind(this, record)}>
        <FormattedMessage id='提交'/>
      </Button>
    </div>
  }

  getInputValue (e) {
    this.setState({deleteProgram: e.target.value})
  }

  hashCode (str) {
    let h = 0
    let off = 0
    let len = str.length
    for (let i = 0; i < len; i++) {
      h = 31 * h + str.charCodeAt(off++)
    }
    return h + ''
  }

  encrypt (type, programId, enable) {
    enable = enable ? 1 : 0
    return this.hashCode(`${type}`) + enable + '.' + this.hashCode(`${type}${programId}${programId}`) + '.' + programId
  }

  getRegisterUrl (type, programId, enable) {
    let {settings} = this.props
    const code = this.encrypt(type, programId, enable)
    const context = settings.appContextPath === '/learn' ? '' : 'staging.'
    const link = `http://${context}school.thoughtworks.cn/learn/auth/register?code=${code}`
    return link
  }

  getOrganizations = (programId) => {
    const {user, organizations} = this.props
    return <Menu>
      {organizations.filter(organization => organization.id !== user.currentOrganizationId)
        .map(organization =>
          <Menu.Item>
            <Popconfirm
              okText={<FormattedMessage id='确定'/>}
              cancelText={<FormattedMessage id='取消'/>}
              title={<span><FormattedMessage id='确定要复制到'/> {organization.title}?</span>}
              onConfirm={() => this.copyProgramToOrganization(programId, organization.id)}>
              <a>{organization.title}</a>
            </Popconfirm>
          </Menu.Item>
        )
      }

    </Menu>
  }
  copyProgramToOrganization = (programId, organizationId) => {
    this.props.copyProgramToOrganization(programId, organizationId, () => {
      this.setModalVisible(false)
    })
  }
  copyProgram = (programId) => {
    this.props.copyProgram(programId, () => {
      this.setModalVisible(false)
    })
  }
  deleteProgram = programId => {
    const {page, pageSize} = this.state
    this.props.deleteProgram(programId, page, pageSize, () => {
      message.success(convertContent('删除成功'))
      this.setState({modalVisible: false})
    })
  }

  toDiff = programId => {
    const {settings} = this.props
    const {diffUrl,appContextPath} = settings
    if (!appContextPath) {
      window.location.href = `http://localhost:3000/#/programs/${programId}`
      return
    }
    if (appContextPath === '/learn') {
      window.location.href = `https://school.thoughtworks.cn${diffUrl}#/programs/${programId}`
      return
    }

    window.location.href = `https://staging.school.thoughtworks.cn${diffUrl}#/programs/${programId}`
  }

  moreInfo (program) {
    const programName = program.title
    const optionals = ['付费', '免费']
    const programList = [program]
    const columns = [{
      title: <FormattedMessage id='开始时间'/>,
      dataIndex: 'startTime',
      render: (text, record) => (
        <DateCell
          value={text}
          id={record.id}
          onChange={value => this.onCellChange(value, 'startTime', record)}
        />
      )
    },
      {
        title: <FormattedMessage id='结束时间'/>,
        dataIndex: 'endTime',
        render: (text, record) => (
          <DateCell
            value={text}
            id={record.id}
            onChange={value => this.onCellChange(value, 'endTime', record)}
          />
        )
      },
      {
        title: <FormattedMessage id='类型'/>,
        dataIndex: 'category',
        render: (text, record) => (
          <SelectStatus
            value={text}
            id={record.id}
            onChange={value => this.onCellChange(value, 'category', record)}
            optionals={optionals}
          />
        )
      },
      {
        title: <FormattedMessage id='操作'/>,
        dataIndex: 'operation',
        render: (text, record) => (
          <span>
            <span>
              <Popconfirm
                okText={<FormattedMessage id='确定'/>}
                cancelText={<FormattedMessage id='取消'/>}
                title={<span><FormattedMessage id='确定要复制吗?'/></span>}
                onConfirm={() => this.copyProgram(record.id)}>
                <a><FormattedMessage id='复制'/></a>
              </Popconfirm>
            </span>
            <span className='ant-divider'/>
             <span>
            <Popconfirm
              okText={<FormattedMessage id='确定'/>}
              cancelText={<FormattedMessage id='取消'/>}
              title={<span><FormattedMessage id='确认删除?'/></span>}
              onConfirm={() => this.deleteProgram(record.id)}>
              <a><FormattedMessage id='删除'/></a>
            </Popconfirm>
            </span>
            <span className='ant-divider'/>
            {this.props.organizations.length > 1 ?
              <span>
               <span className='ant-divider'/>
              <span>
                  <Dropdown
                    trigger={['click']}
                    overlay={this.getOrganizations(record.id)}>
                    <a className='ant-dropdown-link' href='#'>
                      <FormattedMessage id='复制到其它组织'/><Icon type='down'/>
                    </a>
                  </Dropdown>
              </span>
            </span>
              : ''
            }
        </span>)
      }
    ]
    const content = (
      <Table dataSource={programList} columns={columns} pagination={false} rowKey={record => record.id}/>)
    this.setState({content, programName})
    this.setModalVisible(true)
  }

  render () {
    let {programPage, settings} = this.props
    const programList = programPage.content
    const {expandRowByClick, expandIconAsCell, expandedRowKeys, page, pageSize, programName, modalVisible, content} = this.state
    const columns = [{
      title: <FormattedMessage id='名称'/>,
      dataIndex: 'title',
      width: '20%',
      render: (text, record) => {
        return (
          <EditableCell
            isProgram
            isReadOnly={record.readOnly}
            value={text}
            id={record.id}
            linkUrl={this.changeShow(record.id)}
            onChange={value => this.onCellChange(value, 'title', record)}
          />
        )
      }
    },
      {
        title: <FormattedMessage id='训练营介绍'/>,
        dataIndex: 'introduction',
        width: '25%',
        render: (text, record) => {
          return <Row>
            <Col span={22} className='col' style={{width: 250}}>
              <span>{text}</span>
            </Col>
            {
              record.readOnly
                ? ''
                : <Col span={2} style={{float: 'right'}}>
                  {this.switchIcon(record)}
                </Col>
            }

          </Row>
        }
      },
      {
        title: <FormattedMessage id='是否只读'/>,
        dataIndex: 'readOnly',
        width: '8%',
        render: (text, program) => {
          return <Switch
            checkedChildren={<FormattedMessage id='开'/>}
            unCheckedChildren={<FormattedMessage id='关'/>}
            onChange={isReadOnly => this.onCellChange(isReadOnly, 'readOnly', program)}
            checked={text}
          />
        }
      }, {
        title: <FormattedMessage id='是否过期'/>,
        dataIndex: 'expired',
        width: '8%',
        render: (text, program) => {
          return <Switch
            checkedChildren={<FormattedMessage id='开'/>}
            unCheckedChildren={<FormattedMessage id='关'/>}
            onChange={isExpired => this.onCellChange(isExpired, 'expired', program)}
            checked={text}
          />
        }
      },
      {
        title: <FormattedMessage id='学员注册链接'/>,
        dataIndex: 'studentLink',
        width: '10%',
        render: (enable, record) => (
          <div style={{textAlign: 'center'}}>
            <Switch
              checkedChildren={<FormattedMessage id='开'/>}
              unCheckedChildren={<FormattedMessage id='关'/>}
              onChange={enable => this.props.updateProgramLink('student', record.id, enable, page, pageSize)}
              defaultChecked={enable}/>
            {enable
              ? <CopyToClipboard text={this.getRegisterUrl('student', record.id, enable)}
                                 onCopy={() => message.success(convertContent('复制成功'))}>
                <a><FormattedMessage id='复制链接'/></a>
              </CopyToClipboard>
              : ''
            }
          </div>
        )
      },
      {
        title: <FormattedMessage id='助教注册链接'/>,
        dataIndex: 'tutorLink',
        width: '10%',
        render: (enable, record) => (
          <div style={{textAlign: 'center'}}>
            <Switch
              checkedChildren={<FormattedMessage id='开'/>}
              unCheckedChildren={<FormattedMessage id='关'/>}
              onChange={enable => this.props.updateProgramLink('tutor', record.id, enable, page, pageSize)}
              defaultChecked={enable}/>
            {enable
              ? <CopyToClipboard text={this.getRegisterUrl('tutor', record.id, enable)}
                                 onCopy={() => message.success(convertContent('复制成功'))}>
                <a><FormattedMessage id='复制链接'/></a>
              </CopyToClipboard>
              : ''
            }
          </div>
        )
      },
      {
        title: <FormattedMessage id='操作'/>,
        dataIndex: 'operation',
        render: (text, record) => {
          return (
            <span>
            <span>
              <Link to={this.changeShow(record.id)}><FormattedMessage id='进入'/></Link>
            </span>
            <span className='ant-divider'/>
            <span>
              <a href='' onClick={() => this.props.addMyWorkspace(record.id)}><FormattedMessage id='加入我的工作区'/></a>
            </span>
            <span className='ant-divider'/>
              <span>
              <a onClick={() => this.toDiff(record.id)}>Diff</a>
            </span>
            <span className='ant-divider'/>
            <span>
              <a onClick={this.moreInfo.bind(this, record)}><FormattedMessage id='更多'/></a>
            </span>
          </span>
          )
        }
      }]
    const pagination = {
      current: page,
      total: programPage.totalElements,
      pageSize: 20,
      onChange: (page) => {
        this.onChange(page, pageSize)
      }
    }

    return (
      <div>
        <Button type='primary' className='editable-add-btn' onClick={this.handleAdd.bind(this)}><FormattedMessage
          id='新增训练营'/></Button>
        <Table
          className='programList-table'
          bordered
          dataSource={programList}
          columns={columns}
          expandRowByClick={expandRowByClick}
          expandIconAsCell={expandIconAsCell}
          expandedRowKeys={expandedRowKeys}
          expandedRowRender={this.expandedRowRender.bind(this, settings)}
          rowKey={record => record.id}
          pagination={pagination}
          size='middle'
        />
        <Modal
          title={programName}
          centered
          footer={null}
          width={800}
          visible={modalVisible}
          onCancel={() => this.setModalVisible(false)}
        >
          {content}
        </Modal>
      </div>
    )
  }
}

const mapStateToProps = ({user, settings}) => ({
  settings, user
})

const mapDispatchToProps = dispatch => ({
  updateProgramLink: (type, programId, enable, page, pageSize) => dispatch(actions.updateProgramLink({
    type,
    programId,
    enable,
    page,
    pageSize
  })),
  addMyWorkspace: (programId) => dispatch(actions.addMyWorkspace(programId))

})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ProgramManagement))
